#include <iostream>

class TreeNode
{
public:
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode()
    {
        this->val = 0;
        this->left = nullptr;
        this->right = nullptr;
    }

    TreeNode(int x)
    {
        this->val = x;
        this->left = nullptr;
        this->right = nullptr;
    }

    TreeNode(int x, TreeNode *left, TreeNode *right)
    {
        this->val = x;
        this->left = left;
        this->right = right;
    }
};

void PrevTravel(TreeNode *node)
{
    if (node == nullptr)
        return;
    std::cout << node->val << " ";
    PrevTravel(node->left);
    PrevTravel(node->right);
}

void show(TreeNode *root)
{
    PrevTravel(root);
    std::cout << std::endl;
}

TreeNode *CommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
    if (root == nullptr)
    {
        return root;
    }
    if (root->val > p->val && root->val > q->val)
    {
        TreeNode *left = CommonAncestor(root->left, p, q);
        if (left != nullptr)
        {
            return left;
        }
    }
    if (root->val < p->val && root->val < q->val)
    {
        TreeNode *right = CommonAncestor(root->right, p, q);
        if (right != nullptr)
        {
            return right;
        }
    }
    return root;
}

int main()
{
    // 创建二叉树
    TreeNode *root = new TreeNode(4);
    root->left = new TreeNode(3);
    root->right = new TreeNode(6);
    root->left->left = new TreeNode(1);
    root->left->right = new TreeNode(2);
    root->right->left = new TreeNode(5);
    root->right->right = new TreeNode(8);
    show(root);

    TreeNode *result = CommonAncestor(root, root->right, root->left);
    std::cout << "CommonAncestor: " << result->val << std::endl;

    return 0;
}
